package com.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import static org.slf4j.LoggerFactory.getLogger;

@Component
@Aspect
@Order(2)
public class WebLogAcpect {
    private static final Logger logger = getLogger(WebLogAcpect.class);

    /**
     * 获取所有的下属方法为切入点
     */
    @Pointcut(value = "execution(* com.example.controller.DemoController.*(..))")
    public void cutOffPoint() {

    }

    /**
     * 获取方法testmode为切入点
     */
    @Pointcut(value = "execution(* com.example.controller.DemoController.testmode(..))")
    public void cutOffPoint1() {

    }


    @Before("cutOffPoint1()")
    public void beforetest() {
        logger.info("我在test方法之前执行");
    }

    ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Around("cutOffPoint()")
    public Object doAround(ProceedingJoinPoint pjp){
        startTime.set(System.currentTimeMillis());
        logger.info("我是环绕通知执行");
        Object obj;
        try{
            obj = pjp.proceed();

            logger.info("执行返回值 : " + obj);
            logger.info(pjp.getSignature().getName()+"方法执行耗时: " + (System.currentTimeMillis() - startTime.get()));
        } catch (Throwable throwable) {
            obj=throwable.toString();
        }
        return obj;
    }


}
